package conversation

import (
	"coze_for_sdk/controller"
	"coze_for_sdk/model"
	"errors"
	"fmt"
	"strconv"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func List(c *gin.Context) {

	userId := c.GetInt("user_id")

	//分页信息
	page := c.Query("page")
	pageSize := c.Query("page_size")
	pageInt, _ := strconv.Atoi(page)
	pageSizeInt, _ := strconv.Atoi(pageSize)
	offset := (pageInt - 1) * pageSizeInt

	db := model.GetInstance().GetDB()
	var conversations []model.CozeConversation
	if err := db.Model(&model.CozeConversation{}).
		Where("user_id = ?", userId).
		Where("status = ?", model.CozeConversationStatusActive).
		Order("created_at DESC").
		Limit(pageSizeInt).
		Offset(offset).
		Find(&conversations).Error; err != nil {
		//没查到记录
		if errors.Is(err, gorm.ErrRecordNotFound) {
			controller.Success(c, map[string]interface{}{
				"list":  []model.CozeConversation{},
				"total": 0,
			})
		} else {
			controller.Fail(c, controller.BusinessError, err.Error())
		}
		return
	}

	response := make([]map[string]interface{}, 0)
	for _, conversation := range conversations {
		response = append(response, map[string]interface{}{
			"conversation_id": conversation.ConversationId,
			"title":           conversation.Title,
			"created_at":      conversation.CreatedAt.Format("2006-01-02 15:04"),
		})
	}

	fmt.Println("response", response)

	var total int64
	db.Model(&model.CozeConversation{}).
		Where("user_id = ?", userId).
		Where("status = ?", model.CozeConversationStatusActive).
		Count(&total)

	controller.Success(c, map[string]interface{}{
		"list":  response,
		"total": total,
	})
}
